package com.sdp.wx.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Scanner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sdp.core.bizc.utils.SnowFlake;
import com.sdp.wx.db.wx_contract_template.entity.WxContractTemplate;
import com.sdp.wx.db.wx_contract_template.service.IWxContractTemplateService;
import com.sdp.wx.db.wx_repair_vehicle_doc.entity.WxRepairVehicleDoc;
import com.sdp.wx.db.wx_repair_vehicle_doc.service.IWxRepairVehicleDocService;

@RestController
@RequestMapping("/WxOnlyofficeController")
public class WxOnlyofficeController {
	
	@Autowired
	private IWxContractTemplateService iWxContractTemplateService;
	
	@Autowired
	private IWxRepairVehicleDocService iWxRepairVehicleDocService;
	
	@Value("${sdp.filePath}")
    private String filePath;
	
	@Autowired
	private SnowFlake snowFlake;

	/**
	 * 维修合同模板在线编辑回调
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ResponseBody
    @PostMapping(value = "/contractTemplateCallbackSave")
	@Transactional(rollbackFor=Exception.class)
	public void contractTemplateCallbackSave(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter writer = response.getWriter();
		String body = "";
		try {
			Scanner scanner = new Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			body = scanner.hasNext() ? scanner.next() : "";
			scanner.close();
		} catch (Exception ex) {
			writer.write("get request.getInputStream error:" + ex.getMessage());
			return;
		}
		if (body.isEmpty()) {
			writer.write("empty request.getInputStream");
			return;
		}
		JSONObject jsonObj = JSON.parseObject(body);
//		System.out.println("回调参数对象 =====》》》 " + jsonObj);
		int status = (Integer) jsonObj.get("status");
		int saved = 0;
		// status=6,表示点击保存按钮
		if (status == 6) // MustSave, Corrupted
		{
			InputStream stream = null;
			OutputStream outputStream = null;
			try {
				String key = jsonObj.getString("key");
				String keyId = key.substring(0,key.indexOf("_"));
				LambdaQueryWrapper<WxContractTemplate> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(WxContractTemplate::getKeyId, keyId);
				WxContractTemplate contractTemplateFile = iWxContractTemplateService.getOne(queryWrapper, false);
				if (contractTemplateFile == null) {
					throw new Exception("文件不存在");
				}
				// 获取url
				String downloadUri = (String) jsonObj.get("url");
				// 获取onlyOffice缓存中的文件流
				URL url = new URL(downloadUri);
				java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
				stream = connection.getInputStream();
				if (stream == null) {
					throw new Exception("Stream is null");
				}
			
				// 上传新文件到文件服务器
				String filePath = this.filePath + File.separator + contractTemplateFile.getFilePath();
				// 删除旧文件
				File file = new File(filePath);
				if (file.exists()) {
					file.delete();
				}
		
				File newfile = new File(filePath);
				outputStream = new FileOutputStream(newfile);
				// 这里也很关键每次读取的大小为5M 不一次性读取完
				byte[] buffer = new byte[1024 * 1024 * 5];// 5MB
				int len = 0;
				while ((len = stream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, len);
				}
				connection.disconnect();
				
				contractTemplateFile.setFileKey(snowFlake.nextId()+"");
				iWxContractTemplateService.updateById(contractTemplateFile);
				
			} catch (Exception ex) {
				saved = 3;
				ex.printStackTrace();
			} finally {
				if(outputStream!=null) {
					outputStream.close();
				}
				if(stream!=null) {
					stream.close();
				}
			}
		}
		writer.write("{\"error\":" + saved + "}");
	}
	
	
	/**
	 * 车辆维修单据模板在线编辑回调
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ResponseBody
    @PostMapping(value = "/wxRepairVehicleDocCallbackSave")
	@Transactional(rollbackFor=Exception.class)
	public void wxRepairVehicleDocCallbackSave(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter writer = response.getWriter();
		String body = "";
		try {
			Scanner scanner = new Scanner(request.getInputStream());
			scanner.useDelimiter("\\A");
			body = scanner.hasNext() ? scanner.next() : "";
			scanner.close();
		} catch (Exception ex) {
			writer.write("get request.getInputStream error:" + ex.getMessage());
			return;
		}
		if (body.isEmpty()) {
			writer.write("empty request.getInputStream");
			return;
		}
		JSONObject jsonObj = JSON.parseObject(body);
//		System.out.println("回调参数对象 =====》》》 " + jsonObj);
		int status = (Integer) jsonObj.get("status");
		int saved = 0;
		// status=6,表示点击保存按钮
		if (status == 6) // MustSave, Corrupted
		{
			
			InputStream stream = null;
			OutputStream outputStream = null;
			try {
				String key = jsonObj.getString("key");
				String keyId = key.substring(0,key.indexOf("_"));
				LambdaQueryWrapper<WxRepairVehicleDoc> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(WxRepairVehicleDoc::getKeyId, keyId);
				WxRepairVehicleDoc f = iWxRepairVehicleDocService.getOne(queryWrapper, false);
				if (f == null) {
					throw new Exception("文件不存在");
				}
				// 获取url
				String downloadUri = (String) jsonObj.get("url");
				// 获取onlyOffice缓存中的文件流
				URL url = new URL(downloadUri);
				java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
				stream = connection.getInputStream();
				if (stream == null) {
					throw new Exception("Stream is null");
				}
			
				// 上传新文件到文件服务器
				String filePath = this.filePath + File.separator + f.getFilePath();
				// 删除旧文件
				File file = new File(filePath);
				if (file.exists()) {
					file.delete();
				}
		
				File newfile = new File(filePath);
				outputStream = new FileOutputStream(newfile);
				// 这里也很关键每次读取的大小为5M 不一次性读取完
				byte[] buffer = new byte[1024 * 1024 * 5];// 5MB
				int len = 0;
				while ((len = stream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, len);
				}
				connection.disconnect();
				
				f.setFileKey(snowFlake.nextId()+"");
				iWxRepairVehicleDocService.updateById(f);
				
			} catch (Exception ex) {
				saved = 3;
				ex.printStackTrace();
			} finally {
				if(outputStream!=null) {
					outputStream.close();
				}
				if(stream!=null) {
					stream.close();
				}
			}
		}
		writer.write("{\"error\":" + saved + "}");
	}
}
